 //
//  LessonShareViewController.m
//  LoveDraw
//
//  Created by 梁晨 on 2017/6/13.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "LessonShareViewController.h"
#import "LessonShareTableViewCell.h"

#import "CellForWorkGroup.h"
#import "UITableViewCell+HYBMasonryAutoCellHeight.h"


@interface LessonShareViewController ()<UITableViewDelegate,UITableViewDataSource,CellForWorkGroupDelegate>
{
    NSInteger page;
}

@property(nonatomic,strong)NSMutableArray *requestArr;
@property(nonatomic,strong)UITableView *ListV;
@property(nonatomic,strong)NSMutableArray *ListArr;
@property (nonatomic,strong) NSMutableDictionary *heightDict;
@property (nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong)NSMutableArray *firstArr;

@end

@implementation LessonShareViewController

-(NSMutableArray *)firstArr
{
    if (!_firstArr) {
        _firstArr = [NSMutableArray array];
    }
    return _firstArr;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationItem.title = @"课例共享";
}

#pragma mark --- 懒加载
-(UITableView *)ListV
{
    if (!_ListV) {
        _ListV = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KscreenW, KscreenH-64) style:(UITableViewStyleGrouped)];
        _ListV.delegate = self;
        _ListV.dataSource = self;
        _ListV.separatorStyle = 0;
        _ListV.backgroundColor = [UIColor whiteColor];
        _ListV.estimatedSectionHeaderHeight = 0;
        _ListV.estimatedSectionFooterHeight = 0;
        [_ListV registerClass:[LessonShareTableViewCell class] forCellReuseIdentifier:@"LessonShareTableViewCell"];
         [_ListV registerClass:[CellForWorkGroup class] forCellReuseIdentifier:NSStringFromClass([CellForWorkGroup class])];
    }
    return _ListV;
}
- (NSMutableDictionary *)heightDict{
    if (!_heightDict) {
        _heightDict = [NSMutableDictionary new];
    }
    return _heightDict;
}
-(NSMutableArray *)ListArr
{
    if (!_ListArr) {
        _ListArr = [NSMutableArray array];
    }
    return _ListArr;
}

-(NSMutableArray *)requestArr
{
    if (!_requestArr) {
        _requestArr = [NSMutableArray array];
    }
    return _requestArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.ListV];
    page = 0;

    self.ListV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        page = 1;
        [self requestDataLoadNew:YES];
    }];
    self.ListV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        page++;
        [self requestDataLoadNew:YES];
    }];
    [self.ListV.mj_header beginRefreshing];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.ListArr.count == 0) {
        self.ListV.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"nodata"]];
    }else
    {
        self.ListV.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@""]];
    }
    return self.ListArr.count;;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YHWorkGroup *model  = self.ListArr[indexPath.row];

    CellForWorkGroup *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CellForWorkGroup class])];

    if (!cell) {
        cell = [[CellForWorkGroup alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([CellForWorkGroup class])];
    }

    [cell hiddenYincang];
    cell.indexPath = indexPath;
    cell.model     = model;
    cell.delegate  = self;

//    model.shouldShowMoreButton = YES;


    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < self.ListArr.count) {

        CGFloat height = 0.0;
        YHWorkGroup *model  = self.ListArr[indexPath.row];

        //取缓存高度
        NSDictionary *dict =  self.heightDict[model.dynamicId];
        if (dict) {
            if (model.isOpening) {
                height = [dict[@"open"] floatValue];
            }else{
                height = [dict[@"normal"] floatValue];
            }
            if (height) {
                return height;
            }
        }
        height = [CellForWorkGroup hyb_heightForTableView:tableView config:^(UITableViewCell *sourceCell) {
            CellForWorkGroup *cell = (CellForWorkGroup *)sourceCell;

            cell.model = model;

        }];

//        //缓存高度
//        if (model.dynamicId) {
//            NSMutableDictionary *aDict = [NSMutableDictionary new];
//            if (model.isOpening) {
//                [aDict setObject:@(height) forKey:@"open"];
//            }else{
//                [aDict setObject:@(height) forKey:@"normal"];
//            }
//            [self.heightDict setObject:aDict forKey:model.dynamicId];
//        }

        return height;
    }else{
        return 44.0f;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return FLT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return FLT_MIN;
}

#pragma mark - 网络请求
- (void)requestDataLoadNew:(BOOL)loadNew
{
    if (self.cid) {

    }else
    {
        self.cid = @"";
    }
    [RequestManager RequstWithUrl:@"/index.php?g=App&m=StudentCourseep&a=index" parmDic:@{@"cid":self.cid,@"page":[NSString stringWithFormat:@"%ld",page]} requestType:RequestGET Success:^(id data)
    {

        self.firstArr = [data mutableCopy];

        if (page == 1) {
            [self.requestArr removeAllObjects];
            [self.ListArr removeAllObjects];
        }
        if (self.firstArr.count==0)
        {
            page--;
        }

        [self.requestArr addObjectsFromArray:self.firstArr];

        [self.ListV.mj_footer endRefreshing];
        [self.ListV.mj_header endRefreshing];

        if (self.firstArr.count == 0||self.firstArr.count<10)
        {
            self.ListV.mj_footer.state = MJRefreshStateNoMoreData;
        }

        NSInteger totalCount = self.firstArr.count;
        NSUInteger lastDynamicID = 0;

        if (!loadNew && self.requestArr .count) {
            YHWorkGroup *model = self.requestArr.lastObject;
            lastDynamicID = [model.dynamicId integerValue];
        }

        for (int i=0; i<totalCount; i++)
        {
            YHWorkGroup *model = [YHWorkGroup new];
            model.dynamicId = [NSString stringWithFormat:@"%lu", lastDynamicID + i+1];
            [self randomModel:model totalCount:i];
            [self.ListArr addObject:model];
        }
             [self.ListV reloadData];
    } error:^(NSError *error) {

    }];

}

#pragma mark - 模拟产生数据源
- (void)randomModel:(YHWorkGroup *)model totalCount:(int)totalCount{

    [self creatOriModel:model totalCount:totalCount];

}


- (void)creatOriModel:(YHWorkGroup *)model totalCount:(int)totalCount{

    NSDictionary *dic = self.firstArr[totalCount];

    NSLog(@"muarr[====%@",self.firstArr[0][@"title"]);




    model.msgContent = dic[@"title"];
    model.title = dic[@"coursename"];
    model.bottomLeft = dic[@"addtimedesc"];
    model.bottomRight = dic[@"teachername"];
    model.avatar = dic[@"teacherthumb"];

    //原图
    NSArray *thumbsArr = dic[@"thumbs"];

    NSArray *Bigimage = thumbsArr;

    NSMutableArray *oriPName = [NSMutableArray array];

    for (NSString *imageUrlStr in Bigimage)
    {

        [oriPName addObject:[NSString stringWithFormat:@"%@%@",KUrl,imageUrlStr]];
    }

    NSMutableArray *oriPArr = [NSMutableArray new];
    for (NSString *pName in oriPName) {
        [oriPArr addObject:[NSURL URLWithString:pName]];
    }

    //小图
    NSArray *smallArr =dic[@"thumbs"];
    NSMutableArray *thumbPName = [NSMutableArray array];

    for (NSString *smallPic in smallArr)
    {
        NSString *small = [NSString stringWithFormat:@"%@%@",KUrl,smallPic];

        [thumbPName addObject:[small stringByReplacingOccurrencesOfString:@"/thumb" withString:@""]];
    }

    NSMutableArray *thumbPArr = [NSMutableArray new];
    for (NSString *pName in thumbPName) {
        [thumbPArr addObject:[NSURL URLWithString:pName]];
    }

    model.originalPicUrls = thumbPArr;
    model.thumbnailPicUrls =oriPArr ;

}

#pragma mark - CellForWorkGroupDelegate
- (void)onAvatarInCell:(CellForWorkGroup *)cell{

}

- (void)onMoreInCell:(CellForWorkGroup *)cell{
    if (cell.indexPath.row < [self.ListArr count]) {
        YHWorkGroup *model = self.ListArr[cell.indexPath.row];
        model.isOpening = !model.isOpening;
        [self.ListV reloadRowsAtIndexPaths:@[cell.indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)onDeleteInCell:(CellForWorkGroup *)cell{

    NSIndexPath *indexpath = [self.ListV indexPathForCell:cell];
        [self _deleteDynAtIndexPath:indexpath dynamicId:cell.model.dynamicId];

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息提示框" message:@"是否确认删除该课例？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alert show];

}
//按钮点击事件的代理
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if(buttonIndex==1){
//        [self.navigationController showSuccessTips:@"删除成功"];
//
//        [self.dataArray removeObjectAtIndex:self.indexPath.row];
//        //        [self.tableView beginUpdates];
//        //        [self.tableView deleteRowsAtIndexPaths:@[self.indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//        //        [self.tableView endUpdates];
//        //
//        [self.tableView reloadData];
//
//        // [self.navigationController popToRootViewControllerAnimated:YES];
//    }
//}

#pragma mark - private
- (void)_deleteDynAtIndexPath:(NSIndexPath *)indexPath dynamicId:(NSString *)dynamicId
{

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
